import 'dart:convert';

import 'package:xws/helpers/as_t.dart';

/// 聊天室类型
enum RoomType { SYSTEM, USER }

const List<String> _msgTypes = <String>['SYSTEM', 'USER'];

extension ExMT on RoomType {
  String get str => _msgTypes[index];
}

RoomType _getType(String k) {
  if (k == 'SYSTEM')
    return RoomType.SYSTEM;
  else
    return RoomType.USER;
}

/// 单个聊天对象（聊天室）
class ChatObj {
  ChatObj({
    required this.id,
    required this.type,
    required this.relationId,
    required this.fromUserId,
    required this.fromUserNickName,
    required this.fromUserAvatarUrl,
    required this.toUserId,
    required this.toUserNickName,
    required this.toUserAvatarUrl,
    required this.unreadCount,
    required this.createdAt,
    required this.updatedAt,
    required this.goodsId,
    required this.goodsTitle,
  });

  factory ChatObj.fromJson(Map<String, dynamic> jsonRes) {
    final Map<String, dynamic> g = asT<Map<String, dynamic>>(json.decode(jsonRes['goodsInfo'].toString()));

    return ChatObj(
      id: asT<String>(jsonRes['id']),
      type: _getType(asNullT<String>(jsonRes['type']) ?? 'SYSTEM'),
      relationId: asT<String>(jsonRes['relationId']),
      fromUserId: asT<String>(jsonRes['fromUserId']),
      fromUserNickName: asT<String>(jsonRes['fromUserNickName']),
      fromUserAvatarUrl: asT<String>(jsonRes['fromUserAvatarUrl']),
      toUserId: asT<String>(jsonRes['toUserId']),
      toUserNickName: asT<String>(jsonRes['toUserNickName']),
      toUserAvatarUrl: asT<String>(jsonRes['toUserAvatarUrl']),
      unreadCount: asT<int>(jsonRes['unreadCount']),
      createdAt: asT<String>(jsonRes['createdAt']),
      updatedAt: asT<String>(jsonRes['updatedAt']),
      goodsId: asT<String>(g['goodsId']),
      goodsTitle: asT<String>(g['goodsName']),
    );
  }

  final String id;
  final RoomType type;
  final String relationId;
  final String fromUserId;
  final String fromUserNickName;
  final String fromUserAvatarUrl;
  final String toUserId;
  final String toUserNickName;
  final String toUserAvatarUrl;
  late int unreadCount;
  final String createdAt;
  final String updatedAt;
  final String goodsId;
  final String goodsTitle;

  String get unRead => unreadCount > 99 ? '99+' : unreadCount.toString();
}
